<?php

declare (strict_types = 1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Model\Article;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Phper666\JwtAuth\Jwt;
use Tbqphplib\Hyperfbase\AbstractController;

class IndexController extends AbstractController
{
    /**
     * @Inject
     *
     * @var Jwt
     */
    protected $jwt;
    public function index()
    {
        $user = $this->request->input('user', 'Hyperf');
        $method = $this->request->getMethod();

        return [
            'method' => $method,
            'message' => "Hello {$user}.",
        ];
    }
    public function getById()
    {
        //获取token中的用户数据
        $user = $this->jwt->getParserData();

        $rt = Db::table('articles')->first();
        return $this->success($rt);
    }
    public function create()
    {
        //获取token中的用户数据
        $user = $this->jwt->getParserData();
        $id = $this->request->input('id');
        $id = (int) $id;
        $title = $this->request->input('title');
        $content = $this->request->input('content');
        $articleData = [
            'title' => $title,
            'content' => $content,
            'created_by' => $user['id'],
            'updated_by' => $user['id'],
        ];
        if ($id) {
            $rt = Db::table('articles')
                ->where('id', $id)
                ->update($articleData);
        } else {
            $rt = Article::query()->firstOrCreate($articleData);
        }

        return $this->success($rt);
    }
    function list() {
        $paginator = Db::table('articles')->select('id', 'title')->paginate((int) $this->request->input('limit', 20));
        // return $paginator;
        $rt = [
            'total' => Db::table('articles')->count(),
            'items' => $paginator->items(),
        ];
        return $this->success($rt);
    }
}
